﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using WebAPI.Model;
using static System.Net.Mime.MediaTypeNames;

namespace WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ValueController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public ValueController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        [HttpGet]
        public string Test()
        {
            return "Hello World!";
        }

        /// <summary>
        /// 返回测试模型列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string GetTestModelList()
        {
            List<TestModel> list = new List<TestModel>();

            list.Add(new TestModel { ID = 0, Name = "张三", Description = "CTFer", Time = DateTime.Now });

            list.Add(new TestModel { ID = 1, Name = "李四", Description = "黑客", Time = DateTime.Now });

            string listString = JsonSerializer.Serialize(list);
            var list2 = JsonSerializer.Deserialize<List<TestModel>>(listString);

            return listString;
        }

        [HttpPost]
        public string Test(SearchReq req)
        {
            return "OK" + req.Name;
        }


        [HttpGet]
        public async Task<string> Get()
        {
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7139/api/Value/Test")
            {
                Headers =
                {
                    //设置请求头
                }
            };
            var httpClient = _httpClientFactory.CreateClient();

            var httpResponseMessage = httpClient.Send(httpRequestMessage);
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                var result = await httpResponseMessage.Content.ReadAsStringAsync();
                return result;
            }
            else
            {
                return "请求失败";
            }

        }

        [HttpPost]
        public async Task<string> Post()
        {
            SearchReq req = new SearchReq();
            req.Name = "张三";
            req.Description = "猫叔";
            req.PageSize = 10;
            req.PageIndex = 1;

            //包装参数
            var reqJson = new StringContent(
                JsonSerializer.Serialize(req),
                Encoding.UTF8,
                Application.Json
                );

            var httpClient = _httpClientFactory.CreateClient();

            using var httpResponseMessage = await httpClient.PostAsync("https://localhost:7139/api/Value/Test", reqJson);

            var result = await httpResponseMessage.Content.ReadAsStringAsync();
            return result;
        }
    }
}
